package com.ruoyi.orderManagement.service.impl;

import java.util.List;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ruoyi.orderManagement.config.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.orderManagement.mapper.OrderMapper;
import com.ruoyi.orderManagement.domain.Order;
import com.ruoyi.orderManagement.service.IOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 我的订单Service业务层处理
 * 
 * @author lcd
 * @date 2025-08-14
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService 
{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 查询我的订单
     * 
     * @param orderId 我的订单主键
     * @return 我的订单
     */
    @Override
    public Order selectOrderByOrderId(String orderId)
    {
        return orderMapper.selectOrderByOrderId(orderId);
    }

    /**
     * 查询我的订单列表
     * 
     * @param order 我的订单
     * @return 我的订单
     */
    @Override
    public List<Order> selectOrderList(Order order)
    {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增我的订单
     * 
     * @param order 我的订单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrder(@RequestBody Order order)
    {
        // 如果订单金额未设置，但设置了团队ID和合同期限，则根据团队信息计算订单金额
        // 这里需要根据团队ID查询团队信息，获取团队价格
        // if (order.getOrderPrice() == null && order.getTeamId() != null) {
        //     DocTeam team = teamService.selectDocTeamById(order.getTeamId());
        //     if (team != null) {
        //         order.setOrderPrice(team.getTeamPrice().multiply(new BigDecimal(order.getContractDuration())));
        //     }
        // }
        int result = orderMapper.insertOrder(order);
        // 向RabbitMQ的普通队列发送消息
        rabbitTemplate.convertAndSend("order.exchange2", "order.key.normal2", order);
        return result;
    }


    /**
     * 修改我的订单
     * 
     * @param order 我的订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order)
    {
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除我的订单
     * 
     * @param orderIds 需要删除的我的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderIds(List<String> orderIds)
    {
        return orderMapper.deleteOrderByOrderIds(orderIds);
    }

    /**
     * 删除我的订单信息
     * 
     * @param orderId 我的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderId(String orderId)
    {
        return orderMapper.deleteOrderByOrderId(orderId);
    }

    @Override
    public List<Order> getOrderByUserId(Long userId, String orderState) {
        return orderMapper.getOrderByUserId(userId, orderState);
    }

    @Override
    @Transactional
    public void updateOrderStatus(String orderId, String orderState) {
        orderMapper.updateOrderStatus(orderId, orderState);
    }

    @Override
    public String pay(String orderId) {
        //通过id查询订单
        Order order = orderMapper.getOrderById(orderId);
        log.info("Queried order: {}", order);
        if (order == null) {
            throw new RuntimeException("Order not found for orderId: " + orderId);
        }
        //创建交易页面的支付请求对象
        AlipayTradePagePayRequest request = getAlipayTradePagePayRequest(order);
        String form;
        try {
            //调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
            log.info("支付宝支付表单：" + form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            //让事务回滚
            throw new RuntimeException(e.getMessage());
        }
        //返回表单给控制器
        return form;
    }
    @Autowired
    private AlipayClient alipayClient;   //支付宝提供的客户端
    @Autowired
    private AlipayConfig alipayConfig;   //使用自定义配置类与Alipay中一个类同名
    /**
     * 创建交易页面的支付请求对象
     */
    private AlipayTradePagePayRequest getAlipayTradePagePayRequest(Order order) {
        //1.准备支付的参数，包括需要支付的订单的id，价格，物品名称
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(order.getOrderId()); // 需要支付的订单id，自定义的订单id，不能重复，唯一，已经支付的无法继续支付
        model.setTotalAmount(order.getOrderPrice().toString()); // 需要支付的钱
        model.setSubject("订单"); // 要支付的物品，比如 model.setSubject("Iphone6 16G");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");  //销售产品码，电脑支付场景就使用FAST_INSTANT_TRADE_PAY
        // 2.创建支付的请求，设置上面的准备支付的参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setBizModel(model);
        // 3.设置支付宝异步回调，这个需要用内网穿透
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        // 4.设置支付宝支付成功返回的页面，这里让支付成功直接回到static下的一个静态页面中
        request.setReturnUrl(alipayConfig.getReturnUrl());
        return request;
    }
}
